package main

import (
	. "local/algorithm/util"
)

/*
*
A B C D E
C B A D E

第一步圈定要翻转的范围
第二步执行翻转
![](http://cdn.bsummer.cn/20191204123134.png)
*/
func reverseKGroup(head *ListNode, k int) *ListNode {
	node := head
	for i := 0; i < k; i++ {
		if node == nil { //
			return head
		}
		node = node.Next
	}

	newhead := reverse(head, node)
	head.Next = reverseKGroup(node, k)
	return newhead
}

func reverse(i, j *ListNode) *ListNode {
	prev := j
	current := i
	for current != j {
		tmp := current.Next
		current.Next = prev
		prev = current
		current = tmp
	}

	return prev
}

func main() {
	list := GenerateLinkedList([]int{1, 2, 3, 4, 5})
	newList := reverseKGroup(list, 2)
	PrintLinkedList(newList)
}
